// models/orderItem.js
const { DataTypes } = require("sequelize");
const sequelize = require("../config/database");

const OrderItem = sequelize.define(
  "OrderItem",
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      comment: "订单项唯一标识符",
    },
    orderId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: "关联订单ID",
    },
    productId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: "关联商品ID",
    },
    quantity: {
      type: DataTypes.INTEGER,
      allowNull: false,
      validate: {
        min: 1,
      },
      comment: "购买数量",
    },
    price: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false,
      validate: {
        min: 0,
      },
      comment: "购买时的商品单价",
    },
    total: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false,
      validate: {
        min: 0,
      },
      comment: "订单项总价(quantity * price)",
    },
  },
  {
    tableName: "order_items",
    timestamps: true,
    comment: "订单项表，存储订单中的商品信息",
    indexes: [
      {
        name: "K_orderId",
        fields: ["orderId"],
      },
      {
        name: "K_productId",
        fields: ["productId"],
      },
    ],
  }
);

// 订单项关联定义
OrderItem.associate = function (models) {
  // 一个订单项属于一个订单
  OrderItem.belongsTo(models.Order, {
    foreignKey: "orderId",
    as: "order",
  });

  // 一个订单项属于一个商品
  OrderItem.belongsTo(models.Product, {
    foreignKey: "productId",
    as: "product",
  });
};

module.exports = OrderItem;
